package com.huarun.common.util;

import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

/**
 * @author hqy
 * @创建时间   2018-08-13 15:02
 * @Description 文件服务器
 */
//@Component
public class FastDFSUtil {
	@Autowired
	FastFileStorageClient fastFileStorageClient;

	public String upload(MultipartFile file) throws IOException {
		String fullPath = "";
		StorePath storePath = fastFileStorageClient.uploadFile(null, file.getInputStream(), file.getSize(),
				getSuffix(file.getOriginalFilename()));
		fullPath = Constant.FDFS_IP + storePath.getFullPath();

		return fullPath;
	}

	public void download(String fileUrl) {
		StorePath storePath = StorePath.praseFromUrl(fileUrl);
		byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(),
				new DownloadByteArray());
		FileOutputStream stream = null;
		try {
			//			File file = new File(
			//					"d:/img" + File.separator + System.currentTimeMillis() + "." + getSuffix(storePath.getPath()));
			//			stream = new FileOutputStream(file);
			stream = new FileOutputStream(System.currentTimeMillis() + "." + getSuffix(storePath.getPath()));
			stream.write(bytes);
			stream.flush();
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (stream != null) {
					stream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 文件删除
	 * @param fileUrl
	 */
	public void deleteFile(String fileUrl) {
		StorePath storePath = StorePath.praseFromUrl(fileUrl);
		fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
	}

	/**
	 * 获取文件后缀名
	 * @param fileName
	 * @return
	 */
	private String getSuffix(String fileName) {
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		return suffix;
	}
}
